/* $RCSFile: CacheManager.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/CacheManager/CacheManager.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:18  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:45  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Globalization;

using AddonNice.UI.WebControls;
using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Settings.Cache;
using AddonNice.Core;
using AddonNice.Helpers;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Country;
using AddonNice.UI.DataTypes;
using AddonNice.Design;
using AddonNice.CRMWrapper;

using AddonNice.Utilities;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using Cache2    =   AddonNice.Settings.Cache.CurrentCache;

namespace AddonNice.PageModules.CacheManager
{

    public class AStr
    {
        public const string ShowDetail      =   "CACHEMANAGER_SHOWDETAIL";
        public const string UseExternal     =   "CACHEMANAGER_USEEXTERNAL";
    }
    /// <summary>
    /// Initializer class for CacheManager 
    /// </summary>
    public class CacheManagerSI : PortalCRMModuleControlSI
    {
        public CacheManagerSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose || CacheManagerTrace.Sw.TraceWarning )
                Trace2.WriteLine( "[V]CacheManagerSI Ctor BEG.",( ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:CacheManagerTrace.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose || CacheManagerTrace.Sw.TraceWarning )
                Trace2.WriteLine( "[V]CacheManagerSI Ctor END.",( ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:CacheManagerTrace.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CacheManagerSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            string extgrp                       =   pm.ExtendedResourcesGroup;

			SettingItemSpecial ShowDetail	    =	new SettingItemSpecial(AStr.ShowDetail,new BooleanDataType());
			ShowDetail.Value		            =	StStr.strFalse;        
			ShowDetail.Order		            =	10;        
			ShowDetail.ExtendedGroupName        =   extgrp;
            ShowDetail.Description		        =	"Show detailled values for all items";
			ShowDetail.EnglishName		        =	"Show Details";
			bSettings.AddSetting(ShowDetail);


			SettingItemSpecial UseExternal	    =	new SettingItemSpecial(AStr.UseExternal,new BooleanDataType());
			UseExternal.Value		            =	StStr.strFalse;        
			UseExternal.Order		            =	30;        
			UseExternal.ExtendedGroupName       =   extgrp;
            UseExternal.Description		        =	"Use External";
			UseExternal.EnglishName		        =	"Use External";
			bSettings.AddSetting(UseExternal);
        }
    }

	/// <summary>
	///	Summary description for CacheManager.
	/// </summary>
	public partial class CacheManager : PortalCRMModuleControl
    {

        /// <summary>
        /// No entity needed here
        /// </summary>
        public override bool NeedAttachedEntity
        {
            get
            {
                return false;
            }
        }

        bool useExternal
        {
            get
            {
                return portalSettings.CustomSettings[StStr.SiteSettingsUseCacheManager].ToBool() && Settings[AStr.UseExternal].ToBool();
            }
        }

        
        #region General module Implementation

        /// <summary>
		/// General Module Def GUID
		/// </summary>
		public override Guid GuidID 
		{
			get
			{
				return new Guid("{0320419A-6DC2-4ddb-BB1B-98B66C4AB8B4}");
			}
		}

		/// <summary>
		/// Admin Module
		/// </summary>
		public override bool AdminModule
		{
			get
			{
				return true;
			}
		}

        #endregion General module Implementation


        /// <summary>
		/// CacheManager Constructor
		/// Set the Module Settings
		/// </summary>
		public CacheManager()
		{
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                 =   "CACHEMANAGER";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new CacheManagerSI(bSettings,this);
        }

		protected void Page_Load(object sender, EventArgs e)
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose || CacheManagerTrace.Sw.TraceWarning )
                Trace2.WriteLine( "[V]CacheManagerSI Page_Load CALLED.",( ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:CacheManagerTrace.Sw.Info);
		}

        /// <summary>
        /// Build a table with cache items
        /// </summary>
        DataTable MakeCacheTb()
        {
            if ( CacheManagerTrace.Sw.TraceWarning )
                Trace2.WriteLine( "[V]CacheManagerSI MakeCacheTb BEG.",CacheManagerTrace.Sw.Info);
            bool ShowDetail             =   Settings[AStr.ShowDetail].ToBool();
            if ( !useExternal )
                return CacheHelper.MakeCacheTb(ShowDetail);
            Utilities.Utilities cacheUtil   =   new AddonNice.Utilities.Utilities();
            cacheUtil.Url               =   portalSettings.CustomSettings[StStr.SiteSettingsPublicSiteUrl].ToString().Trim()+"/services/utilities.asmx";
            return cacheUtil.GetCacheTable(Config.CacheHandShake,ShowDetail);
        }


		/// <summary>
		/// Rebind the DataSet To DataTable
		/// </summary>
        void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            if ( CacheManagerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CacheManager RadGrid1_NeedDataSource BEG.",CacheManagerTrace.Sw.Info);
            try
			{
                LbSize.Text         =   string.Format("PrivateBytesLimit: {0} Kb, EffectivePercentagePhysicalMemoryLimit: {1}%", HttpRuntime.Cache.EffectivePrivateBytesLimit/1024,HttpRuntime.Cache.EffectivePercentagePhysicalMemoryLimit);
                LbCount.Text        =   string.Format("Objects in cache: {0}", HttpRuntime.Cache.Count);
				RadGrid1.DataSource =   MakeCacheTb();
			}
			catch (Exception ex)
			{
				if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CacheManager RadGrid1_NeedDataSource ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
			}
            if ( CacheManagerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CacheManager RadGrid1_NeedDataSource END.",CacheManagerTrace.Sw.Info);
		}

        /// <summary>
        /// remove one Cache item
        /// </summary>
		protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
		{
            GridDataItem dataItem   =   (GridDataItem)e.Item;
            string key              =   dataItem.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Key"].ToString();
            if ( CacheManagerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CacheManager RadGrid1_DeleteCommand BEG Key: {0}", key),CacheManagerTrace.Sw.Info);
            try
            {
                Cache2.Remove(key);
                RadGrid1.DataSource =   null;
                RadGrid1.Rebind();
            }
            catch (Exception ex)
            {
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CacheManager RadGrid1_DeleteCommand Key: {0}, ex: {1}", key, ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
		}

        /// <summary>
        /// remove selected Cache items
        /// </summary>
        void RadGrid1_ItemCommand(object source,GridCommandEventArgs e)
        {
            if ( CacheManagerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CacheManager RadGrid1_ItemCommand BEG e.CommandName: {0}", e.CommandName),CacheManagerTrace.Sw.Info);
            if ( e.CommandName != "DeleteSelected" )
                return;
            try
            {
                foreach ( GridDataItem it in RadGrid1.SelectedItems )
                {
                    string key              =   it.OwnerTableView.DataKeyValues[it.ItemIndex]["Key"].ToString();
                    Cache2.Remove(key);
                }
                RadGrid1.DataSource =   null;
                RadGrid1.Rebind();
            }
            catch (Exception ex)
            {
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CacheManager RadGrid1_ItemCommand ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if ( CacheManagerTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CacheManager RadGrid1_ItemCommand END e.CommandName: {0}", e.CommandName),CacheManagerTrace.Sw.Info);
        }

        #region Std Overrides

		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}
		
		private void InitializeComponent()
		{
			Load					+=	new EventHandler(this.Page_Load);
            RadGrid1.DeleteCommand  +=  new GridCommandEventHandler(RadGrid1_DeleteCommand);
            RadGrid1.NeedDataSource +=  new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
            RadGrid1.ItemCommand    +=  new GridCommandEventHandler(RadGrid1_ItemCommand);
		}

		#endregion
	}
}
